# coding=utf-8

import thread
import time

import web
from web.utils import storage

import settings
import utils

import controllers.admin.partners.models as partner_models
import controllers.admin.projects.models as proj_models

import models
from forms import discountinfo_form, top10_form

#from controllers.admin.widgets import destination_dropdown
from controllers.admin.administrators import auth_login

render = settings.RENDER

class DispatchTop10Mails(object):
    """
    发送 Top10 订阅邮件
    """
    def POST(self):
        # 获取最新一期的特惠Top10
        posts = models.get_last_TOP10()
        # 构造邮件内容
        mail = storage(body = self.make_mail(posts)
                , subject = '【最新Top10】寻宝图本周特惠追踪精选%s出版通知！' % utils.int2date(posts[0].date, '%(month)s月%(day)s日'))
        # 开启新的线程
        #thread.start_new_thread(self.dispatch, (posts[0].date, mail,))
        self.dispatch(posts[0].date, mail)
        return 0

    def dispatch(self, last_send, mail):
        """发送邮件（后台运行）"""
        # 获取收件人列表
        usrs = models.get_subscribes(last_send)
        for usr in usrs:
            # 发送邮件
            utils.week_mail(usr.email
                    , mail.subject
                    , mail.body.__body__ % usr.email)
            # 更新最后发送时间，避免重复发送
            models.update_subscribe_lastsend(usr.id, last_send)
            # 进程休眠
            time.sleep(0.3)
        # 退出线程
        thread.exit_thread()


    def make_mail(self, posts):
        """构造订阅邮件内容"""
        if posts:
            return render.admin.discounts.mail_dispatch_top10(posts[0])

        return None


class Delete(object):
    def GET(self, id):
        id = utils.intval(id)
        # 删除成功的标记
        flag = 'false'
        # 删除给定记录并跳转
        if models.delete_discount_by_id(id):
            flag = 'true'
        # 无论成功失败都跳转到列表
        raise web.seeother('/discount?del=%s' % flag)

class Top10(object):
    """
    特惠信息TOP10
    """
    @auth_login
    def GET(self, date = '0'):
        ipt = web.input()
        # 表单实例
        f = top10_form()
        # 是否处于编辑状态
        date = utils.intval(date)
        if date > 0:
            # 读取记录
            post = models.get_discount_top10(date)
            if post:
                # 给表单赋值
                f.date.value = str(post.date_index)
                f.date.attrs['data-value'] = utils.int2date(f.date.value)
                f.discount_info_ids.value = post.discount_info_ids
                f.submit.attrs['html'] = u'修改甄选TOP30'
                # 读取选取的特惠信息列表
                sposts = models.get_discounts_by_ids(f.discount_info_ids.value)
                if sposts:
                    shtml = u'''
                            <dt id="sel_len">
                                已选择：<strong>%s</strong> 项
                            </dt>''' % len(sposts)
                    for spost in sposts:
                        shtml += u'''
                        <dd related="%(id)s">
                            — <a href="/discounts/%(id)s" target="_blank">%(tit)s</a>
                        </dd>''' % {'id': spost.id, 'tit': spost.title}

                    f.discount_info_html.value = shtml
        # 当前页
        page = utils.intval(ipt.get('page', '0'))
        # 每页记录数
        perpage = 15
        # 获取列表
        r = models.get_discount_top10s(page * perpage, perpage)
        # 创建分页器
        pager = utils.Pager(r.totalrecords, pageindex = page)
        # 渲染页面
        return render.admin.discounts.top10(f, r, pager)

    def POST(self, date = '0'):
        f = top10_form()
        date = utils.intval(date)
        # 表单验证
        if f.validates():
            if date > 0:
                # 更新
                models.update_discount_top10(date, f)
            else:
                # 新增
                models.add_discount_top10(f)

            # 保存成功，跳转
            raise web.seeother('/discount/top10')

        # 各种验证失败
        return render.admin.discounts.top10(f)

class Index(object):
    """
    特惠信息管理列表
    """
    @auth_login
    def GET(self):
        ipt = web.input()
        # 当前页码
        page = utils.intval(ipt.get('page', '0'))
        # 每页记录数
        perpage = 20
        # 读取列表
        r = models.get_discounts(page * perpage, perpage)
        # 获取渲染模式
        mode = ipt.get('mode', '')

        # 创建分页器
        pager = utils.Pager(r.totalrecords
                , pageindex = page
                , pagesize = perpage
                , link = '<a href="?page=%(page)s&mode='+mode+'">%(text)s</a>')

        if mode == 'lite':
            # 渲染精简模式
            return render.admin.discounts.index_lite(r, pager)
        else:
            # 显示到页面的消息
            msg = None
            # 是否来自删除后的跳转
            fdel = ipt.get('del', None)
            if fdel:
                if utils.cmp_i(fdel, 'true') == 0:
                    msg = '删除成功'
                else:
                    msg = '删除失败'

            # 渲染常规模式
            return render.admin.discounts.index(r, pager, msg)

class Add(object):
    """
    添加特惠信息
    """
    @auth_login
    def GET(self, id = '0'):
        f = discountinfo_form()
        # 目的地id，在编辑模式时赋值
        #dest_id = None
        id = utils.intval(id)
        if id > 0:
            # 进入编辑状态
            info = models.get_discount_by_id(id)
            if info:
                #dest_id = info.dest_id
                f.proj_id.value = str(info.proj_id)
                # 尝试读取项目名称
                if info.proj_id > 0:
                    # 读取项目名称
                    proj = proj_models.Project.get(info.proj_id)
                    if proj:
                        f.proj_name.value = proj.name
                        f.proj_type.value = proj.type

                f.partner_id.value = str(info.partner_id)
                # 尝试读取合作商家的名称
                if info.partner_id > 0:
                    # 读取合作商家的名称
                    partner = partner_models.get_partner(info.partner_id)
                    if partner:
                        f.partner_name.value = partner.name

                f.url.value = info.url
                if utils.date_is_valid(info.expire):
                    f.expire.value = info.expire
                f.title.value = info.title
                f.price.value = str(info.price)
                f.discount.value = str(info.discount)
                f.is_initial_price.checked = info.is_initial_price == 1
                f.lightning.checked = info.lightning == 1
                f.directing.checked = info.directing == 1
                f.price_index.value = str(info.price_index)
                f.depart_id.value = info.depart_id
                #f.short_text.value = info.short_text
                f.media_id.value = str(info.media_id)
                # 转换媒体文件的地址
                f.media_url.value = utils.get_media_url(info.media_id, 3)
                f.content.value = info.content
                f.booking_tips.value = info.booking_tips
                # 更改提交按钮测试
                f.submit.attrs['html'] = u'修改信息'

        # 生成目的地下拉控件
        #dest_dropdown = destination_dropdown('dest_id'
        #        , None
        #        , dest_id
        #        , dflt_val = u''
        #        , required = 'required'
        #        , message = '请选择目的地；'
        #        , class_ = 'txt'
        #        , tabindex = 5)

        # 是否来自保存后的转向
        ipt = web.input(saved = None)

        return render.admin.discounts.add(f, ipt.saved)

    @auth_login
    def POST(self, id = '0'):
        """ 保存添加 """
        f = discountinfo_form()
        if f.validates():
            # 插入标志
            insert_id = 0
            # 表单验证成功
            id = utils.intval(id)
            if id > 0:
                # 这里是编辑信息使用
                if models.update_discount_by_form(id, f):
                    raise web.seeother('/discount/edit/%s?saved=true' % id)
            else:
                # 新增信息
                insert_id = models.add_discount_by_form(f)
                # 跳转到修改页
                if insert_id > 0:
                    raise web.seeother('/discount/edit/%s?saved=true' % insert_id)
            
        # 表单验证失败
        # 保存失败
        # 等，各种失败
        return render.admin.discounts.add(f)
